package com.springcloud1.gateway.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * zuul拦截器，过滤请求
 */
@Component
public class CustomZuulFilter extends ZuulFilter  {
    @Override
    public String filterType() {
        return "pre"; //pre 路由前执行； route 路由请求时执行；error 处理请求时发生错误时被调用；post 在route和error过滤器之后被调用；
    }

    @Override
    public int filterOrder() {
        return 0; //过滤器的执行顺序。当请求在一个阶段中存在多个过滤器时，需要根据该方法返回的值来依次执行。
    }

    @Override
    public boolean shouldFilter() {
        //RequestContext ctx = RequestContext.getCurrentContext();
        return true; //判断该过滤器是否需要被执行，true 执行，false 不执行。 可以利用该函数来指定过滤器的有效范围
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("====> CustomZuulFilter.run");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request=ctx.getRequest();
        HttpServletResponse response=ctx.getResponse();
        //处理跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Authorization,X-Requested-With");
        //权限验证等...
        if(request.getHeader("token")==null || "".equals(request.getHeader("token").toString())){
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            return false;
        }
        return null;
    }
}
